package src

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/sirupsen/logrus"
)

/*
统计角色的openid与unionid的关联
*/

type (
	wxInfo struct {
		openids []string
		//cnt     int
	}
)

var (
	gUids map[string]*wxInfo = make(map[string]*wxInfo) //unionid-->openid集
)

func DoStatWxUid() {
	//readf("20240824_19_15_22.log")
	readDir()

	logrus.Info("*************** totao guids:", len(gUids))
	for k, v := range gUids {
		if len(v.openids) > 1 {
			fmt.Printf(">>>>>>>>>>> k:%s v:%+v len:%d\n", k, v, len(v.openids))
			//panic(fmt.Sprintf(">>>>>>>>>>> k:%s v:%+v len:%d\n", k, v, len(v.openids)))
			logrus.Errorf(">>>>>>>>>>> k:%s v:%+v len:%d\n", k, v, len(v.openids))
		}
	}
}

func readDir() {
	var (
		paths = []string{"log", "log/old"}
	)
	for _, path := range paths {
		ds, err := os.ReadDir(path)
		if err != nil {
			log.Fatalf("read dir:%s err:%+v", path, err)
		}
		fmt.Println("--------- dir:", path)

		for _, v := range ds {
			if v.IsDir() {
				continue
			}
			if !strings.Contains(v.Name(), ".log") || strings.Contains(v.Name(), "_out") || strings.Contains(v.Name(), "_err") {
				continue
			}
			//fmt.Println(">>> file:", v.Name())
			readf(path + "/" + v.Name())
			/* if k == 5 {
				return
			} */
		}
	}
}

func readf(fs string) {
	f, err := os.Open(fs)
	if err != nil {
		log.Fatalf("read file:%s, err:%+v", fs, err)
		return
	}
	defer f.Close()

	var n int
	scan := bufio.NewScanner(f)
	for scan.Scan() {
		//fmt.Printf(">>>>>:%s\n", scan.Text())
		/* logrus.WithFields(logrus.Fields{
			"file": fs,
			"line": scan.Text(),
		}).Info("txt") */
		parseUid(scan.Text())
		n++
	}
	if err := scan.Err(); err != nil {
		log.Fatal("scan err:", err)
	}

	//fmt.Println("read n:", n)
	/* logrus.WithFields(logrus.Fields{
		"readN": n,
	}).Info("normal") */
	//logrus.Info("readN:", n)
}

func parseUid(str string) []string {
	var (
		vs []string
	)

	if !strings.Contains(str, "weixin access token") {
		return vs
	}

	s := "OpenId:"
	if i := strings.Index(str, s); i != -1 {
		vs = append(vs, str[i+len(s):i+len(s)+28])
	}

	s = "UnionId:"
	if i := strings.Index(str, s); i != -1 {
		vs = append(vs, str[i+len(s):i+len(s)+28])
	}
	if len(vs) != 2 {
		//logrus.Warnf("vs != 2:%+v", vs)
		return vs
	}

	if _, ok := gUids[vs[1]]; !ok {
		gUids[vs[1]] = &wxInfo{openids: []string{vs[0]}}
	} else {
		fg := false
		for _, v := range gUids[vs[1]].openids {
			if v == vs[0] {
				fg = true
				break
			}
		}
		if !fg {
			gUids[vs[1]].openids = append(gUids[vs[1]].openids, vs[0])
		}
	}
	//fmt.Println("uids:", vs)
	return vs
}
